// @Author : zaniu(zzaniu@126.com)
// @Time   : 2021/9/6 18:09
// @Desc   :
//
//                   _ooOoo_
//                  o8888888o
//                  88" . "88
//                  (| -_- |)
//                  O\  =  /O
//               ____/`---'\____
//             .'  \\|     |//  `.
//            /  \\|||  :  |||//  \
//           /  _||||| -:- |||||-  \
//           |   | \\\  -  /// |   |
//           | \_|  ''\---/''  |   |
//           \  .-\__  `-`  ___/-. /
//         ___`. .'  /--.--\  `. . __
//      ."" '<  `.___\_<|>_/___.'  >'"".
//     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
//     \  \ `-.   \_ __\ /__ _/   .-` /  /
// =====`-.____`-.___\_____/___.-`____.-'=====
//                   `=---='
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//           佛祖保佑       永无BUG
//
package main

import (
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/model"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"log"
	"os"
	"path"
	"time"
)

func main() {
	str, _ := os.Getwd()
	// create clientConfig
	clientConfig := constant.ClientConfig{
		// we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		NamespaceId:          "eb15ed13-004f-4655-be73-a1d1ff654f98",
		TimeoutMs:            5000,
		NotLoadCacheAtStart:  true,
		LogDir:               path.Join(str, "/utils/nacos/tmp/log"),
		CacheDir:             path.Join(str, "/utils/nacos/tmp/cache"),
		RotateTime:           "24h",
		MaxAge:               3,
		LogLevel:             "debug",
		UpdateCacheWhenEmpty: false, // 当service返回的实例列表为空时，不更新缓存，用于推空保护
	}

	// At least one ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      "120.236.12.126",
			ContextPath: "/nacos",
			Port:        8848,
			Scheme:      "http",
		},
	}

	// Another way of create naming client for service discovery (recommend)
	namingClient, err := clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		fmt.Println("创建服务发现的客户端失败, err = ", err.Error())
		os.Exit(-1)
	}
	registerFlag := true
	if registerFlag {
		ok, err := namingClient.RegisterInstance(vo.RegisterInstanceParam{
			Ip:          "127.0.0.1",
			Port:        8083,
			ServiceName: "user.go",
			Weight:      10,
			Enable:      true,
			Healthy:     true,
			Ephemeral:   true,
			Metadata:    map[string]string{"idc": "shanghai"},
			ClusterName: "user-a", // default value is DEFAULT
			GroupName:   "user-a", // default value is DEFAULT_GROUP
		})
		if err != nil {
			fmt.Println("注册失败, err = ", err.Error())
			os.Exit(-1)
		}
		if ok {
			fmt.Println("注册成功")
		} else {
			fmt.Println("注册失败")
		}
	}

	services, err := namingClient.GetService(vo.GetServiceParam{
		ServiceName: "user.go",
		// Clusters:    []string{"user-a"}, // 默认值DEFAULT
		// GroupName:   "user-a",             // 默认值DEFAULT_GROUP
	})
	if err != nil {
		fmt.Println("获取失败， err = ", err.Error())
		os.Exit(-1)
	}
	fmt.Println("services = ", services)
	for _, service := range services.Hosts {
		fmt.Println("service = ", service)
	}

	// 订阅
	err = namingClient.Subscribe(&vo.SubscribeParam{
		ServiceName: "demo.go",
		GroupName:   "user-a",           // 默认值DEFAULT_GROUP
		Clusters:    []string{"user-a"}, // 默认值DEFAULT
		SubscribeCallback: func(services []model.SubscribeService, err error) {
			log.Println("services = ", services)
		},
	})
	time.Sleep(time.Second * 60)
	// 配置中心demo (recommend)
	// configClient, err := clients.NewConfigClient(
	// 	vo.NacosClientParam{
	// 		ClientConfig:  &clientConfig,
	// 		ServerConfigs: serverConfigs,
	// 	},
	// )
}
